package arithmetic.guaveTest;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 *
 * 需求:
 * 当有同一个人的多张表同时变化时,(或者短时间内反复变化时),  不希望缓存反复刷新,希望赞在一起只刷新一次
 *
 * 目标:
 * 利用实现guava缓存失效时,执行下缓存的刷新
 *
 * 结果: 不行,guava 过期时并不会实时通知,只有用了才知道, 可以主动使用invalid 和clearUp来实现
 *  换用expireMap
 * @author jiangfeng
 * Created on 2020-04-09
 */
public class TimerCall {



    public static void main(String[] args) throws InterruptedException {
        Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).removalListener((notification)->{
            System.out.println(">>缓存移除:"+notification.getKey());
            System.out.println(notification.getCause());
            System.out.println( notification.getKey());
        }).build();

        List<String> datas = Lists.newArrayList("a","b","c","a","d","b","e","a");

        ThreadPoolExecutor
                executor = new ThreadPoolExecutor(12*2, 12 * 2, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(20));

        //LoadingCache.

        // 慢慢放缓存
        executor.execute(()->{
            for (String data : datas) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //cache.getIfPresent(data)
                cache.put(data, LocalDateTime.now().toString());
                cache.cleanUp();
            }
        });

        executor.execute(()->{
            int emptyClose =3;
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ImmutableMap<String, String> allPresent = cache.getAllPresent(Sets.newHashSet(datas));
                System.out.println("现有缓存:" + allPresent);
                // 3次为空就关闭打印
                if (allPresent.size() == 0) {
                    if ((--emptyClose) == 0) {
                        break;
                    }
                } else {
                    emptyClose = 3;
                }

            }
        });



        TimeUnit.SECONDS.sleep(300);
    }
}
